/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package me.zhy.math;

/**
 *
 * @author Moon
 */
public class MathUtilities {

    public static double multiply(Point point0, Point point1) {
        return point0.getX() * point1.getX() + point0.getY() * point1.getY();
    }

    public static Point minus(Point point0, Point point1) {
        return new Point(point0.getX() - point1.getX(), point0.getY() - point1.getY());
    }

    public static double distance(Point point, Line line) {
        double x = point.getX();
        double y = point.getY();
        double a = line.getA();
        double b = line.getB();
        double c = line.getC();
        return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
    }

    public static double distance(Point point, LineSegment lineSeg) {
        Point point0 = lineSeg.getPoint0();
        Point point1 = lineSeg.getPoint1();
        {
            Point p0 = minus(point, point0);
            Point pp0 = minus(point1, point0);
            if (multiply(p0, pp0) < 0) {
                return p0.length();
            }
        }
        {
            Point p1 = minus(point, point1);
            Point pp1 = minus(point0, point1);
            if (multiply(p1, pp1) < 0) {
                return p1.length();
            }
        }
        {
            Line line = lineSeg.getLine();
            return distance(point, line);
        }
    }
}
